package thread;

public class SyncDemo1    {
    /*static boolean success1 = false;
    static boolean success2 = false;

    public static void main(String[] args) throws InterruptedException {
        Bank bank = new Bank();
        int sum = 0;
        while(true){
            sum++;
            Thread t1 = new Thread(){
                public void run(){
                    success1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread(){
                public void run(){
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            Thread.sleep(10);
            if(success1==true&&success2==true){
                System.out.println("卡bug成功！共计"+sum+"次");
                break;
            }else{
                System.out.println("正常。");
                success1 = false;
                success2 = false;
                bank.saveAccount(20000);
            }
        }


    }*/

    static boolean success1 = false;
    static boolean success2 = false;

    public static void main(String[] args) throws InterruptedException {

        Bank bank = new Bank();
        int num = 0;
        while(true){
            num++;
            Thread t1 = new Thread(){
                public void run(){
                    success1 = bank.getMoney(20000);

                }
            };
            Thread t2 = new Thread(){
                public void run(){
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            Thread.sleep(10);
            if(success1==true&&success2==true){
                System.out.println("卡bug成功！共"+num+"次。");
                break;
            }else{
                System.out.println("正常");
                success1=false;
                success2=false;
                bank.setAccount(20000);
            }
        }



    }
}
/*class Bank{
    private int account = 20000;
    public void saveAccount(int account){
        this.account=account;
    }
    public int getAccount(){
        return account;
    }
    public synchronized boolean  getMoney(int money){

        int account = getAccount();
        if(account>=money){
            account = account - money;
            Thread.yield();// 让当前线程从运行状态转为就绪状态
                            //模拟本次时间片用完
            saveAccount(account);
            return true;
        }
        return false;
    }

}*/

class Bank{
    private int account=20000;
    public int getAccount(){
        return account;
    }
    public void setAccount(int account){
        this.account = account;
    }
    public boolean getMoney(int money){
        int account = getAccount();
        if(account>=money){
            account=account-money;
            Thread.yield();
            setAccount(account);
            return true;
        }
        return false;
    }
}
